<?php
require_once 'init_app.php';

set_time_limit(0);

$products = ORM::factory('product')
            ->where('is_image', '=', 0)
            ->where('is_available', '=', 1)
            ->offset(0)
            ->limit(100000)
            ->find_all();

foreach ($products as $product) { 
    try { 
        $dir = APPPATH.'../../img.cashbackdoc.com/products/';
        $dir = $dir.sprintf('%02x/', $product->id % 0xff);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%02x/', $product->id % 0xcf);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%02x/', $product->id % 0x8f);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%02x/', $product->id % 0x4f);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%d/', $product->id);
        if (!is_dir($dir)) {
            mkdir($dir);
        }

        $filenamebegin = $dir.Model_Main::translit($product->name);
        $filename = $filenamebegin.'-small.jpg';
        $data = file_get_contents($product->picture);
        $f = fopen($filename, 'w+');
        fputs($f, $data);
        fclose($f); 
        
        $f = fopen($filenamebegin.'-1.jpg', 'w+');
        fputs($f, $data);
        fclose($f);

        $image = Image::factory($filename); 
        $image->resize(245, null)->save();   
        
        $data = DB::select()
                    ->from('product_data')
                    ->where('product_id', '=', $product->id)
                    ->execute()
                    ->as_array();
        if (isset($data[0]) && isset($data[0]['images']) && $data[0]['images']) {
            $images = explode('||', $data[0]['images']);
            $i = 2;
            foreach ($images as $image) {
                if ($image == $product->picture) {
                    continue;    
                }
                $data = file_get_contents($image);
                $f = fopen($filenamebegin.'-'.$i.'.jpg', 'w+');
                fputs($f, $data);
                fclose($f);
                $i++;
            }    
        }
        
        $product->is_image = 1;
        $product->save();
    } catch (Exception $e) {
        //echo $e->getMessage();
        //die();
        continue;
    }
}
